#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef struct
{
    int *arr;        // 数组
    int capacity;    // 容量
    int size;        // 元素个数
    int extendRatio; // 扩容倍数
} MyList_t, *MyList_p;

// 创建顺序表
MyList_p newMyList()
{
    MyList_p nums = (MyList_p)malloc(sizeof(MyList_t));
    nums->size = 0;
    nums->capacity = 10;
    nums->extendRatio = 2;
    nums->arr = (int *)malloc(sizeof(int) * nums->capacity);

    return nums;
}

// 数组扩容
void expand(MyList_p nums)
{
    nums->capacity *= nums->extendRatio;
    int *newArr = (int *)malloc(sizeof(int) * nums->capacity);
    for (int i = 0; i < nums->capacity; i++)
    {
        if (i < nums->size)
        {
            newArr[i] = nums->arr[i];
        }
        else
        {
            newArr[i] = 0;
        }
    }
    free(nums->arr);
    nums->arr = newArr;
}

// 尾部添加
void push(MyList_p nums, int value)
{
    if (nums->size == nums->capacity)
    {
        expand(nums);
    }
    nums->arr[nums->size] = value;
    nums->size++;
}

// 指定位置删除
int delete(MyList_p nums, int index)
{
    if (index < 0 || index >= nums->size)
    {
        return -1;
    }
    for (int i = index; i < nums->size - 1; i++)
    {
        nums->arr[i] = nums->arr[i + 1];
    }
    return --nums->size;
}

// 尾部删除
int pop(MyList_p nums)
{
    if (nums->size == 0)
    {
        return -1;
    }
    return delete(nums, nums->size - 1);
}

// 析构函数
void delMyList(MyList_p nums)
{
    free(nums->arr);
    free(nums);
}

// 查找元素
int findIndex(MyList_p nums, int value)
{
    for (int i = 0; i < nums->size; i++)
    {
        if (nums->arr[i] == value)
        {
            return i;
        }
    }
    return -1;
}

// 打印顺序表
void print(MyList_p nums)
{
    printf("当前列表size=%d,capacity:%d,extendRatio:%d arr=%p 如下:\n", nums->size, nums->capacity, nums->extendRatio, nums->arr);
    for (int i = 0; i < nums->size; i++)
    {
        printf("%d ", nums->arr[i]);
    }
    printf("\n");
}

int main()
{
    MyList_p nums = newMyList();
    // printf("num = %p\n", nums);
    // printf("num = %d\n", (*nums).size);
    // printf("num = %d\n", (*nums).capacity);
    // printf("num = %d\n", (*nums).extendRatio);
    // printf("num = %d\n", nums->arr);

    // 测试末尾添加
    for (int i = 0; i < 25; i++)
    {
        push(nums, i);
    }
    print(nums);

    delete(nums, 5);
    print(nums);

    delMyList(nums);
    return 0;
}